import PropTypes from 'prop-types'
import React, { memo, useEffect, useRef, useState } from 'react'
import { ViewWrapper } from './style'
import IconArrowLeft from '@/assets/svg/icon-arrow-left'
import IconArrowRight from '@/assets/svg/icon-arrow-right'

const ScrollView = memo((props) => {
  /*定义内部状态 */ 
  const [showLeftBtn, setShowLeftBtn] = useState(false)
  const [showRightBtn, setShowRightBtn] = useState(false)
  const [posIndex, setPosIndex] = useState(0)
  const totalDistanceRef =useRef()

  // 获取div实例scrollContentRef
  const scrollContentRef = useRef()

  // 组件渲染完毕，判断是否显示按钮
  useEffect(() => {
    const scrollWidth = scrollContentRef.current.scrollWidth // dom元素内容区的真实宽度
    const clientWidth = scrollContentRef.current.clientWidth // 当前可视的宽度
    const totalDistance = scrollWidth - clientWidth // 总共可以滚动的距离

    totalDistanceRef.current = totalDistance
    setShowRightBtn(totalDistance > 0)
  }, [props.children])

  /* 事件处理的逻辑 */
  // 右边按钮点击事件
 const handleBtnClick = (isRight) => {
  // 更新索引，指向下一个元素

  const newIndex =isRight? posIndex + 1: posIndex - 1
  // 获取下一个元素
  const newElement = scrollContentRef.current.children[newIndex]
  // 应用transform样式，将内容右移100像素
  scrollContentRef.current.style.transform = `translate(-${newElement.offsetLeft}px)`
  // 更新状态
  setPosIndex(newIndex)
  setShowRightBtn(totalDistanceRef.current > newElement.offsetLeft)
  setShowLeftBtn(newElement.offsetLeft > 0)
}

 
  return (
    <ViewWrapper>
      {showLeftBtn &&  (
        <div className='control left' onClick={()=>handleBtnClick(false)}>
        <IconArrowLeft/>
        </div>)
      }
      {showRightBtn &&  (
        <div className='control right' onClick={()=>handleBtnClick(true)}>
          <IconArrowRight/>
        </div>)
      }
      
      <div className='scroll'>
        <div className='scroll-content' ref={scrollContentRef}>
          {props.children}
        </div>
      </div>
      
    </ViewWrapper>
  )
})

ScrollView.propTypes = {}

export default ScrollView
